package com.linrui.car.service.impl;

import com.linrui.basic.service.IBaiduAiService;
import com.linrui.basic.utils.AjaxResult;
import com.linrui.basic.utils.LoginContext;
import com.linrui.basic.utils.VelocityUtils;
import com.linrui.car.domain.Car;
import com.linrui.car.domain.CarDetail;
import com.linrui.car.domain.CarOnlineAuditLog;
import com.linrui.car.domain.CarType;
import com.linrui.car.dto.CarOprDto;
import com.linrui.car.es.doc.CarDoc;
import com.linrui.car.es.repository.CarDocRepository;
import com.linrui.car.mapper.CarDetailMapper;
import com.linrui.car.mapper.CarMapper;
import com.linrui.car.mapper.CarOnlineAuditLogMapper;
import com.linrui.car.mapper.CarResourcesMapper;
import com.linrui.car.service.ICarService;
import com.linrui.basic.service.impl.BaseServiceImpl;
import com.linrui.org.domain.Employee;
import com.linrui.org.domain.Shop;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wangronggui
 * @since 2022-11-03
 */
@Service
public class CarServiceImpl extends BaseServiceImpl<Car> implements ICarService {

    @Autowired
    private CarDetailMapper carDetailMapper;

    @Autowired
    private IBaiduAiService aiService;

    @Autowired
    private CarOnlineAuditLogMapper auditLogMapper;

    @Autowired
    private CarMapper carMapper;

    @Autowired
    private CarDocRepository carDocRepository;

    @Autowired
    private CarResourcesMapper carResourcesMapper;

    @Override
    @Transactional
    public void add(Car car){
        // 设置添加时间
        car.setCreatetime(new Date());
        // 设置上下架状态
        car.setState(0);
        // 设置审核状态
        car.setAuditstate(0);
        // 设置车辆的店铺信息
        Employee loginAdmin = LoginContext.getLoginAdmin();
        car.setShopId(loginAdmin.getShop().getId());
        car.setShopname(loginAdmin.getShop().getName());
        // 设置销售人员的信息
        car.setSellerId(loginAdmin.getId());
        super.add(car);
        // 保存carDetail的信息
        CarDetail carDetail = car.getCarDetail();
        carDetail.setCarId(car.getId());
        carDetail.setCartitle(car.getTitle());
        carDetailMapper.insert(carDetail);

        // 自动审核
        String test = car.getTitle()+carDetail.getInfo();
        AjaxResult result = aiService.audit(test,car.getCover(),null);

        // 添加审核日志
        CarOnlineAuditLog log = new CarOnlineAuditLog();
        log.setCarId(car.getId());
        log.setAuditTime(new Date());
        if(result.getSuccess()){
            // 审核通过
            log.setState(1);
            log.setNote("自动审核通过!");
        }else{
            // 审核失败
            log.setState(2);
            log.setNote("审核失败!原因是:"+result.getMessage());
        }
        auditLogMapper.insert(log);

        // 修改车辆的审核状态
        car.setAuditstate(log.getState());
        super.update(car);
    }

    @Override
    @Transactional
    public void delete(Serializable id) {
        carDetailMapper.deleteByCarid(id);
        carResourcesMapper.deleteByCarid(id);
        super.removeById(id);
    }

    @Override
    @Transactional
    public void onsale(CarOprDto carOprDto) {
        // 效验数据
        List<Long> ids = carOprDto.getIds();
        if (ids==null || ids.size()<1)
            throw new RuntimeException("系统异常，参数不对！");
        // 判断是否有未审核通过数据
        int count = carMapper.getAuditTGCount(ids);
        if (count < ids.size()){
            throw new RuntimeException("存在未审核通过数据,请检查后提交!");
        }
        // 将数据存入es
        List<CarDoc> docs = buildEsCarDocObj(ids);
        Iterable<CarDoc> carDocs = carDocRepository.saveAll(docs);
        carDocs.forEach(System.out::println);
        // 修改数据库状态为上架,添加上架时间
        carMapper.onsale(ids);
        // 记录上架日志
        addAuditLog(ids,3);
        //页面静态化实现
        staticPages(carOprDto.getIds());

    }

    private void staticPages(List<Long> carIds) {
        //每个车要有一个静态化页面
        carIds.forEach(carId->{

            //模型 car
            Car car = carMapper.loadById(carId);

            //模板
            String tmplatePath = this.getClass().getClassLoader().getResource("").getPath()
                    +"/templates/carDetail.vm";
            System.out.println(tmplatePath);

            //静态化页面生成的路径
            String protalWebsitePath = "D:\\IdeaProjects\\ronghuanet-car-websites\\ronghuanet-car-portal\\details\\";
            String htmlFilePath =protalWebsitePath + carId+ ".html";
            VelocityUtils.staticByTemplate(car,tmplatePath,htmlFilePath);
        });
    }

    private List<CarDoc> buildEsCarDocObj(List<Long> ids) {
        List<CarDoc> docs = new ArrayList<>();
        List<Car> cars = carMapper.getCarDetailByIds(ids);
        for (Car car : cars) {
            CarDoc doc = new CarDoc();
            // 快速复制对象
            BeanUtils.copyProperties(car, doc);
            // 设置店铺信息
            Shop shop = car.getShop();
            if(Objects.nonNull(shop)){
                doc.setShopId(shop.getId());
                doc.setShopName(shop.getName());
                doc.setShopAddress(shop.getAddress());
            }
            // 设置类型信息
            CarType type = car.getType();
            if(Objects.nonNull(type)){
                doc.setTypeId(type.getId());
                doc.setTypeName(type.getName());
            }
            // 设置详情对象的info
            CarDetail carDetail = car.getCarDetail();
            if(Objects.nonNull(carDetail)){
                doc.setCarInfo(carDetail.getInfo());
            }
            docs.add(doc);
        }
        return docs;
    }

    private void addAuditLog(List<Long> ids,Integer state) {
        Employee loginAdmin = LoginContext.getLoginAdmin();
        String note = state == 3 ? "上架":"下架";
        List<CarOnlineAuditLog> logs = new ArrayList<>();
        for (Long id : ids) {
            CarOnlineAuditLog log = new CarOnlineAuditLog();
            log.setCarId(id);
            log.setNote(loginAdmin.getUsername()+"对id为"+id+"进行了"+note);
            log.setState(state);
            log.setAuditTime(new Date());
            log.setAuditId(loginAdmin.getId());
            logs.add(log);
        }
        auditLogMapper.batchInsert(logs);
    }

    @Override
    @Transactional
    public void offsale(List<Long> ids) {
        // 效验数据
        if (ids == null || ids.size() == 0){
            throw new RuntimeException("请选择数据!");
        }
        // 将数据从es删除
        List<CarDoc> docs = new ArrayList<>();
        for (Long id : ids) {
            CarDoc doc = new CarDoc();
            doc.setId(id);
            docs.add(doc);
        }
        carDocRepository.deleteAll(docs);
        // 修改数据库状态为上架,添加上架时间
        carMapper.offsale(ids);
        // 记录上架日志
        addAuditLog(ids,4);
    }
}
